package sanrenxing.teacher.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import sanrenxing.Class.domain.ClassName;
import sanrenxing.teacher.dao.TeacherDao;
import sanrenxing.teacher.dao.impl.TeacherDaoImpl;
import sanrenxing.teacher.domain.RoleName;
import sanrenxing.teacher.domain.Teacher;
import sanrenxing.teacher.domain.TeacherTo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description：对Emp表操作的控制器类
 * @auth：胡标
 * @date:2020/8/26 0026 - 9:58
 * @version:1.0
 */
@WebServlet("/TeacherServlet")
public class TeacherServlet extends HttpServlet {
    //定义数据层对象
    private TeacherDao teacherDao =new TeacherDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");

        //获得请求路径中的操作方式参数
        String method=req.getParameter("method");
        //判断操作方式，执行方法代码
        if("findAll".equals(method)){
            //调用查询所有数据的方法
            findAll(req,resp);
        }else if("add".equals(method)){
            //调用增加员工的方法
            add(req,resp);
        }else if("update".equals(method)){
            //调用修改方法
            update(req,resp);
        }else if("batchDel".equals(method)){
            //调用删除方法
            batchDel(req,resp);
        }else if("delete".equals(method)){
            //删除单行
            delete(req,resp);
        }else if ("findRoleName".equals(method)){
            findRoleName(req,resp);
        }
    }

    /**
     * 查询所有角色
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void findRoleName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
        //定义输出流对象
        PrintWriter out=resp.getWriter();
        //调用方法获取班级名称
        List<RoleName> roleNameList=teacherDao.findRoleName();
        Map<String,Object> map=new HashMap<>();
        map.put("json1",roleNameList);
        Gson gson=new Gson();
        String json1=gson.toJson(map);

        if (json1!=""){
            out.print(json1);
        }else{
            out.print("no");
        }
    }

    /**
     * 批量删除数据
     * @param req 请求对象
     * @param resp 响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    private void batchDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //定义输出流对象
        PrintWriter out=resp.getWriter();
        //得到来自请求中的员工编号字符串
        String teacherIdStr =req.getParameter("str" );
        //对员工编号字符串按","进行分割
        String[] teacherIds=teacherIdStr.split(",");
        //由于是批量删除，使用异常和循环来进行判断删除是否成功
        try{
            //循环删除
            for(String teacherStr:teacherIds){
                //把字符串转换为整型的员工编号
                int teacherId=Integer.parseInt(teacherStr);
                //调用数据层代码进行删除
                teacherDao.delete(teacherId);
            }
            //向客户端发送操作结果
            out.print("ok");
        }catch(Exception e){
            out.print("no");
        }
        //关闭输出流对象
        out.close();
    }

    /**
     * 删除数据
     * @param req 请求对象
     * @param resp 响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //定义输出流对象
        PrintWriter out=resp.getWriter();
        //得到来自请求中的员工编号字符串
        String teacherIdStr =req.getParameter("teacherId");
        try{
            //把字符串转换为整型的员工编号
            int teacherId=Integer.parseInt(teacherIdStr);
            //调用数据层代码进行删除
            teacherDao.delete(teacherId);
            //向客户端发送操作结果
            out.print("ok");
        }catch(Exception e){
            out.print("no");
        }
        //关闭输出流对象
        out.close();
    }

    /**
     * 修改emp表中的员工数据
     * @param req 请求对象
     * @param resp 响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //定义输出对象
        PrintWriter out=resp.getWriter();
        //接收来自前端请求的json数据字符串
        String json=req.getParameter("json");
        //接收职务名称
        String roleName=req.getParameter("roleName");
        //调用数据层方法查询职务的编号
        int roleId=teacherDao.findRoleId(roleName);
        //定义Gson操作对象
        Gson gson = new Gson();
        //通过gson对象将json数据转换成员工对象
        Teacher teacher= null;
        try {
            teacher = gson.fromJson(json, Teacher.class);
            //修改对象中的职务编号
            teacher.setRoleId(roleId);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        //调用数据层方法，实现数据添加
        int rows=teacherDao.update(teacher);
        //判断操作是否成功
        if(rows>0){
            out.print("ok");
        }else{
            out.print("no");
        }
        //关闭输出流对象
        out.close();
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //定义输出对象
        PrintWriter out=resp.getWriter();
        //接收来自前端请求的json数据字符串
        String json=req.getParameter("json");
        //接收职务名称
        String roleName=req.getParameter("roleName");
        //调用数据层方法查询职务的编号
        int roleId=teacherDao.findRoleId(roleName);
        //定义Gson操作对象
        Gson gson = new Gson();
        //通过gson对象将json数据转换成员工对象
        Teacher teacher= null;
        try {
            teacher = gson.fromJson(json, Teacher.class);
            //修改对象中的职务编号
            teacher.setRoleId(roleId);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        //调用数据层方法，实现数据添加
        int rows=teacherDao.add(teacher);
        //判断操作是否成功
        if(rows>0){
            out.print("ok");
        }else{
            out.print("no");
        }
        //关闭输出流对象
        out.close();
    }

    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //创建输出流对象
        PrintWriter out=resp.getWriter();
        //获取当前页数
        String pageStr = req.getParameter("page");
        int page = 1;
        if(pageStr!=null && pageStr.trim().length()!=0){
            page = Integer.parseInt(pageStr);
        }
        //获取每页行数
        String rowsStr = req.getParameter("limit");
        int rows = 5;
        if(rowsStr!=null && rowsStr.trim().length()!=0){
            rows = Integer.parseInt(rowsStr);
        }
        //定义用于构造多条件查询的员工对象
        Teacher teacher= new Teacher();
        //获取来自请求中的班主任姓名
        String teacherName=req.getParameter("teacherName");
        //判断并加入到员工对象中
        if(teacherName!=null && teacherName.trim().length()!=0){
            teacher.setTeacherName(teacherName);
        }
        //调用数据方法，根据员工对象构造查询条件字符串
        String condition=teacherDao.getCondition(teacher);
        //执行多条件分页查询
        List<TeacherTo> teacherToList=teacherDao.findByPage(rows,page,condition);
        //多条件查询表中总记录数
        int totalRows=teacherDao.count(condition);

        //定义映射集合对象
        Map<String,Object> mapData=new HashMap<String,Object>();
        //在映射集合中添加key为code，值为0的状态码
        mapData.put("code",0);
        //在映射集合中添加key为msg,值为响应信息字符串
        mapData.put("msg","");
        //在映射集合中添加key为count,值总行数的数据对
        mapData.put("count",totalRows);
        //在映射集合中添加key为data,值为员集合对象
        mapData.put("data",teacherToList);
        //建立Gson对象
        Gson gson=new Gson();
        //使用Gson对象把映射集合转换为json格式数据
        String json1=gson.toJson(mapData);
        //将json数据输出到客户端
        out.write(json1);
        //关闭输出流对象
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
